package main

import (
	"fmt"
	"os"
	"path/filepath"

	"github.com/cynhard/ticket-system/internal/handlers"
	"github.com/cynhard/ticket-system/internal/middleware"
	"github.com/cynhard/ticket-system/internal/models"
	"github.com/cynhard/ticket-system/internal/services"
	"github.com/cynhard/ticket-system/pkg/utils"
	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
)

func main() {
	// 获取配置文件路径
	configPath := "config/config.yaml"
	if len(os.Args) > 1 {
		configPath = os.Args[1]
	}

	// 解析为绝对路径
	if !filepath.IsAbs(configPath) {
		dir, _ := os.Getwd()
		configPath = filepath.Join(dir, configPath)
	}

	// 加载配置
	config, err := utils.LoadConfig(configPath)
	if err != nil {
		fmt.Printf("加载配置失败: %v\n", err)
		os.Exit(1)
	}

	// 设置Gin模式
	if config.Server.Mode == "release" {
		gin.SetMode(gin.ReleaseMode)
	}

	// 初始化数据库
	var dbType, mysqlDSN, sqlitePath string
	if config.Database.Type == "mysql" {
		dbType = "mysql"
		mysqlDSN = config.GetMySQLDSN()
	} else {
		dbType = "sqlite"
		sqlitePath = config.Database.SQLite.Path
	}

	db, err := models.SetupDB(dbType, mysqlDSN, sqlitePath, config.Database.MySQL.LogMode)
	if err != nil {
		fmt.Printf("数据库初始化失败: %v\n", err)
		os.Exit(1)
	}

	// 初始化服务
	userService := services.NewUserService(db, config.JWT.Secret, config.JWT.ExpireTime)
	ticketService := services.NewTicketService(db)

	// 初始化处理器
	userHandler := handlers.NewUserHandler(userService)
	ticketHandler := handlers.NewTicketHandler(ticketService)

	// 创建Gin引擎
	r := gin.Default()

	// 配置CORS
	r.Use(cors.New(cors.Config{
		AllowOrigins:     []string{"*"},
		AllowMethods:     []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
		AllowHeaders:     []string{"Origin", "Authorization", "Content-Type"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
	}))

	// 健康检查接口
	r.GET("/ping", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "pong",
		})
	})

	// API路由
	api := r.Group("/api")
	{
		// 用户相关接口
		users := api.Group("/users")
		{
			users.POST("/register", userHandler.Register)
			users.POST("/login", userHandler.Login)

			// 需要认证的接口
			authUsers := users.Group("")
			authUsers.Use(middleware.JWTAuth(config.JWT.Secret))
			{
				authUsers.GET("/profile", userHandler.GetProfile)
				authUsers.PUT("/profile", userHandler.UpdateUser)
				authUsers.POST("/change-password", userHandler.ChangePassword)
			}

			// 管理员接口
			adminUsers := users.Group("")
			adminUsers.Use(middleware.JWTAuth(config.JWT.Secret), middleware.AdminAuth())
			{
				adminUsers.GET("", userHandler.ListUsers)
				adminUsers.PUT("/:id", userHandler.UpdateUser)
				adminUsers.DELETE("/:id", userHandler.DeleteUser)
			}
		}

		// 工单相关接口
		tickets := api.Group("/tickets")
		tickets.Use(middleware.JWTAuth(config.JWT.Secret))
		{
			tickets.POST("", ticketHandler.CreateTicket)
			tickets.GET("", ticketHandler.ListTickets)
			tickets.GET("/my", ticketHandler.ListMyTickets)
			tickets.GET("/assigned", ticketHandler.ListAssignedTickets)
			tickets.GET("/:id", ticketHandler.GetTicket)
			tickets.POST("/:id/comments", ticketHandler.AddComment)
			tickets.GET("/:id/comments", ticketHandler.ListComments)

			// 客服/管理员接口
			supportTickets := tickets.Group("")
			supportTickets.Use(middleware.SupportAuth())
			{
				supportTickets.POST("/:id/assign", ticketHandler.AssignTicket)
				supportTickets.POST("/:id/take", ticketHandler.TakeTicket)
				supportTickets.POST("/:id/resolve", ticketHandler.ResolveTicket)
				supportTickets.POST("/:id/close", ticketHandler.CloseTicket)
				supportTickets.GET("/metrics", ticketHandler.GetTicketMetrics)
			}
		}
	}

	// 配置静态文件服务 - 使用特定路径避免与API路由冲突
	r.Static("/static", "./ui/static")
	// 为了前端页面访问方便，将根路径重定向到登录页
	r.GET("/", func(c *gin.Context) {
		c.Redirect(302, "/static/index.html")
	})

	// 启动服务器
	serverAddr := fmt.Sprintf(":%d", config.Server.Port)
	fmt.Printf("服务器正在启动，监听端口: %s\n", serverAddr)
	err = r.Run(serverAddr)
	if err != nil {
		fmt.Printf("服务器启动失败: %v\n", err)
		os.Exit(1)
	}
} 